package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.admin.domain.entity.RaidersEntity;
import com.xbongbong.admin.model.RaidersModel;
import com.xbongbong.admin.pojo.PointPojo;
import com.xbongbong.admin.pojo.vo.PointCardPojo;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.pojo.dto.PaasFormDataEsInitDTO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsInitVO;
import com.xbongbong.paas.service.CompanyConfigService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.AccessLinkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.raiders.enums.RaidersPointChildEnum;
import com.xbongbong.pro.enums.raiders.enums.RaidersStepEnum;
import com.xbongbong.pro.script.pojo.dto.DingtalkTemplateDTO;
import com.xbongbong.pro.script.pojo.dto.RaidersDataDTO;
import com.xbongbong.process.ding.DingtalkWorkrecordService;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.sys.domain.dao.CompanyConfigDao;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.model.CompanyConfigModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 *
 * @author xingxing.xiao
 * @date 2019/12/19 10:00
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/workrecord")
public class DingtalkTemplateController {

    private static final Logger LOG = LoggerFactory.getLogger(DingtalkTemplateController.class);

    @Resource
    private DingtalkWorkrecordService dingtalkWorkrecordService;
    @Resource
    private RaidersModel raidersModel;
    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private CompanyConfigDao companyConfigDao;
    @Resource
    private CompanyConfigService companyConfigService;
    @Resource
    private CompanyConfigModel companyConfigModel;

    /**
     * 修复所有空的待办模板code
     * @author xingxing.xiao
     */
    @RequestMapping(value = "/updateDingtalkCodes", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String updateDingtalkCodes(@RequestBody @Valid DingtalkTemplateDTO dingtalkTemplateDTO) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(dingtalkTemplateDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        Boolean isAll = dingtalkTemplateDTO.getIsAll();
        JSONObject obj = new JSONObject();
        int count = 0;
        if (isAll) {
            // 全部
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("columns", new StringBuffer("id, corpid, config_value "));
            param.put("configAlias", CompanyConfigEnum.DINGTALK_WORKRECORD.getAlias());
            param.put("del", DelEnum.NORMAL.getDel());
            List<CompanyConfigEntity> configList = companyConfigDao.findEntityList(param);
            for (CompanyConfigEntity entity : configList) {
                JSONObject jsonObject = JSONObject.parseObject(entity.getConfigValue());
                String dingtalkProcessCode = jsonObject.getString("dingtalkProcessCode");
                // processCode 是空的就更新
                if (StringUtil.isEmpty(dingtalkProcessCode)) {
                    String reCode = companyConfigService.saveDingtalkProcessTemplate(dingtalkProcessCode, entity.getCorpid());
                    if (StringUtil.isNotEmpty(reCode)) {
                        count ++;
                        jsonObject.put("dingtalkProcessCode", reCode);
                        entity.setConfigValue(jsonObject.toJSONString());
                    }
                }
            }
            companyConfigDao.updateBatchNonCopid(configList);
        }

        obj.put("successCount", "成功更新模板：" + count);
        return obj.toJSONString();
    }

    /**
     * 创建待办模板
     * @author xingxing.xiao
     */
    @RequestMapping(value = "/createWorkrecordTemplate", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String createWorkrecordTemplate(@RequestBody @Valid DingtalkTemplateDTO dingtalkTemplateDTO) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(dingtalkTemplateDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        String corpid = dingtalkTemplateDTO.getCorpid();
        JSONObject obj = new JSONObject();
        int count = 0;
        CompanyConfigEntity companyConfig = companyConfigDao.getByConfigAlias(CompanyConfigEnum.DINGTALK_WORKRECORD.getAlias(), corpid);
        if (Objects.nonNull(companyConfig)) {
            String dingtalkProcessCode = "";
            dingtalkProcessCode = companyConfigService.saveDingtalkProcessTemplate(dingtalkProcessCode, corpid);
            if (!dingtalkProcessCode.isEmpty()) {
                JSONObject jsonObject = JSONObject.parseObject(companyConfig.getConfigValue());
                jsonObject.put("dingtalkProcessCode", dingtalkProcessCode);
                companyConfig.setConfigValue(jsonObject.toJSONString());
                count = companyConfigDao.update(companyConfig);
            }
        } else {
            // 新增
            companyConfigService.insertCompanyWorkrecordConfig(corpid, 1);
            count++;
        }
        obj.put("successCount", "成功创建模板：" + count);
        return obj.toJSONString();
    }


    /**
     * 更新待办模板
     * @author xingxing.xiao
     */
    @RequestMapping(value = "/updateWorkrecordTemplate", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String updateWorkrecordTemplate(@RequestBody @Valid DingtalkTemplateDTO dingtalkTemplateDTO) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(dingtalkTemplateDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        String corpid = dingtalkTemplateDTO.getCorpid();
        Boolean isAll = dingtalkTemplateDTO.getIsAll();
        JSONObject obj = new JSONObject();
        int count = 0;
        if (isAll) {
            // 全部
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("columns", new StringBuffer("id, corpid, config_value "));
            param.put("configAlias", CompanyConfigEnum.DINGTALK_WORKRECORD.getAlias());
            param.put("del", DelEnum.NORMAL.getDel());
            List<CompanyConfigEntity> configList = companyConfigDao.findEntityList(param);
            for (CompanyConfigEntity entity : configList) {
                JSONObject jsonObject = JSONObject.parseObject(entity.getConfigValue());
                String dingtalkProcessCode = jsonObject.getString("dingtalkProcessCode");
                if (StringUtil.isNotEmpty(dingtalkProcessCode)) {
                    String reCode = companyConfigService.saveDingtalkProcessTemplate(dingtalkProcessCode, entity.getCorpid());
                    if (StringUtil.isNotEmpty(reCode)) {
                        count ++;
                    }
                }
            }
            companyConfigDao.updateBatchNonCopid(configList);
        } else {
            // 单个，当前公司
            CompanyConfigEntity companyConfigEntity = companyConfigModel.getByConfigAlias(CompanyConfigEnum.DINGTALK_WORKRECORD.getAlias(), corpid);
            if (Objects.nonNull(companyConfigEntity)) {
                JSONObject jsonObject = JSONObject.parseObject(companyConfigEntity.getConfigValue());
                String dingtalkProcessCode = jsonObject.getString("dingtalkProcessCode");
                if (StringUtil.isNotEmpty(dingtalkProcessCode)) {
                    String reCode = companyConfigService.saveDingtalkProcessTemplate(dingtalkProcessCode, corpid);
                    if (StringUtil.isNotEmpty(reCode)) {
                        count ++;
                        companyConfigDao.update(companyConfigEntity);
                    }
                }
            }
        }

        obj.put("successCount", "成功更新模板：" + count);
        return obj.toJSONString();
    }

    /**
     * 删除单个公司的所有es数据(慎用)
     * copy by 鲁江的方法
     *
     * http://192.168.10.104:2019/pro/v1/workrecord/delEsDataByCorpid
     * {
     *   "frontDev":"1",
     *    "xbbCode":123456,
     *    "corpid": "xbbe1ff7f6a032f495a9405df4d2d60085f",
     *    "userId" : "1495102134939",
     *    "platform":"web",
     *    "saasMark":1,
     *    "byCorpid":1
     * }
     * 需更改 corpid
     *
     * @author xingxing.xiao
     * @date 2019/12/20 10:01
     */
    @RequestMapping(value = "/delEsDataByCorpid", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String delEsDataByCorpid(@RequestBody @Valid PaasFormDataEsInitDTO paasFormDataEsInitDTO, BindingResult br) throws Exception {
        XbbResponse<PaasFormDataEsInitVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(paasFormDataEsInitDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                PaasFormDataEsInitVO paasPrintSaveVO = dingtalkWorkrecordService.deleteAllData(paasFormDataEsInitDTO);
                response = new XbbResponse<>(paasPrintSaveVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 更新价值攻略的数据
     * @author xingxing.xiao
     */
    @RequestMapping(value = "/updateRaidersData", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String updateRaidersData(@RequestBody @Valid RaidersDataDTO raidersDataDTO) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(raidersDataDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        JSONObject obj = new JSONObject();
        int successCount;

        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("del", DelEnum.NORMAL.getDel());
        List<RaidersEntity> raidersList = raidersModel.findEntitys(param);

        Set<Integer> pointKeySet = new HashSet<>();
        for (RaidersEntity entity : raidersList) {
            List<PointPojo> point = JsonHelperUtil.parseArray(JSONArray.toJSONString(entity.getPoint()), PointPojo.class);
            for (PointPojo pointPojo : point) {
                pointKeySet.add(pointPojo.getPointKey());
            }
        }
        Map<Integer, PointCardPojo> keyPointMap = new HashMap<>(pointKeySet.size());
        for (RaidersPointChildEnum cache : RaidersPointChildEnum.values()) {
            if (!pointKeySet.contains(cache.getPointKey())) {
                continue;
            }
            AccessLinkEnum iconColor = cache.getIconColor();
            PointCardPojo cardPojo = new PointCardPojo(cache.getName(), iconColor.getIcon(), iconColor.getColor());
            keyPointMap.put(cache.getPointKey(), cardPojo);
        }

        for (RaidersEntity entity : raidersList) {
            // 1. 攻略分步配置
            // 功能预览
            JSONObject preview = entity.getPreview();
            preview.put("title", RaidersStepEnum.PREVIEW.getName());
            preview.put("summary", RaidersStepEnum.PREVIEW.getInstruction());
            preview.put("button", "体验该功能");
            // 视频介绍
            JSONObject video = entity.getVideo();
            video.put("title", RaidersStepEnum.VIDEO.getName());
            video.put("summary", RaidersStepEnum.VIDEO.getInstruction());
            video.put("button", "查看视频课程");
            // 实操使用
            JSONObject operation = entity.getOperation();
            operation.put("title", RaidersStepEnum.OPERATION.getName());
            operation.put("summary", RaidersStepEnum.OPERATION.getInstruction());
            operation.put("button", "立即去操作");
            // 邀请同事
            JSONObject invitation = entity.getInvitation();
            invitation.put("title", RaidersStepEnum.INVITATION.getName());
            invitation.put("summary", RaidersStepEnum.INVITATION.getInstruction());
            invitation.put("button", "邀请同事");
            // 文档下载
            if (Objects.isNull(entity.getDocument())) {
                JSONObject document = new JSONObject();
                document.put("score", 0);
                document.put("enable", 0);
                document.put("title", RaidersStepEnum.DOCUMENT.getName());
                document.put("summary", RaidersStepEnum.DOCUMENT.getInstruction());
                document.put("button", "文档下载");
                entity.setDocument(document);
            } else {
                JSONObject document = entity.getDocument();
                document.put("title", RaidersStepEnum.DOCUMENT.getName());
                document.put("summary", RaidersStepEnum.DOCUMENT.getInstruction());
                document.put("button", "立即下载");
            }
            // 2. 提取卡片样式配置
            List<PointCardPojo> cardList = new ArrayList<>();
            List<PointPojo> point = JsonHelperUtil.parseArray(JSONArray.toJSONString(entity.getPoint()), PointPojo.class);
            for (PointPojo pointPojo : point) {
                PointCardPojo cardPojo = keyPointMap.get(pointPojo.getPointKey());
                cardList.add(cardPojo);
            }
            JSONArray cardArray = JSONArray.parseArray(JSON.toJSONString(cardList));
            entity.setPointCard(cardArray);
        }

        try {
            successCount = raidersModel.updateSetBatch(raidersList);

            obj.put("total", "需更新数据：" + raidersList.size());
            obj.put("successCount", "成功更新数据：" + successCount);

        } catch (Exception e) {
            obj.put("error", e);
            e.printStackTrace();
        }
        return obj.toJSONString();
    }

}
